<?php

namespace App\Task;

use App\Model\Device;
use Hyperf\Crontab\Annotation\Crontab;

#[Crontab(rule: "* * * * *", name: "DeviceNotOnlineTask", callback: "execute", memo: "定时处理不在线的设备")]
class DeviceNotOnlineTask
{
    public function execute(): void
    {
        // 大于三分钟设置离线
        $min = 5;// 三分钟
        $curr_time = date('Y-m-d H:i:s');
        $decr_time = strtotime($curr_time . "-{$min} minute");
        $time = date('Y-m-d H:i:s', $decr_time);

        // 查询需要设置为离线的设备
        $devices = Device::where('inline', Device::ONLINE)
            ->where('last_online_at', '<', $time)
            ->get();

        foreach ($devices as $device) {
            // 更新设备状态
            $device->inline = Device::NOT_ONLINE;
            $device->fd = null;
            $device->save();
            // 添加设备故障日志记录
            \App\Model\DeviceFaultLog::create([
                'device_id' => $device->id,
                'message' => '设备超过5分钟未在线，被标记为离线状态',
                'created_at' => $curr_time,
                'updated_at' => $curr_time
            ]);
        }
    }
}
